<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;
use app\traits\MyModelTrait;

/**
 * @mixin \think\Model
 */
class AdminUserToken extends Model
{
    use MyModelTrait;

    // 管理员登录态
    // 目的：保持单点登录
    protected $table = 'admin_user_token';

    /**
     * 生成记录
     *
     * @param int    $admin_user_id admin_user.id
     * @param string $token         登录态
     */
    public static function generateLog(int $admin_user_id, string $token): void
    {
        $insert = [
            'admin_user_id' => $admin_user_id,
            'token'         => $token,
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s')
        ];
        self::insert($insert);
    }// generateLog() end

    /**
     * update admin_user_token.token
     *
     * @param int    $admin_user_id admin_user.id
     * @param string $token
     */
    public static function setToken(int $admin_user_id, string $token): void
    {
        $admin = self::whereRaw('admin_user_id = :admin_user_id', ['admin_user_id' => $admin_user_id])->findOrEmpty();
        if ($admin->isEmpty())
        {
            self::generateLog($admin_user_id, $token);
        } else {
            $admin->token = $token;
            $admin->save();
        }
    }// setToken() end
}
